package com.zhu.transaction.service.imp;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.Gson;
import com.zhu.transaction.config.AlipayConfig;
import com.zhu.transaction.mapper.OrderMapper;
import com.zhu.transaction.mapper.UserMapper;
import com.zhu.transaction.pojo.BackCategory;
import com.zhu.transaction.pojo.Order;
import com.zhu.transaction.pojo.OrderItem;
import com.zhu.transaction.pojo.state.AliPayState;
import com.zhu.transaction.pojo.state.BackState;
import com.zhu.transaction.pojo.state.OrderTransactionState;
import com.zhu.transaction.pojo.state.PaymentState;
import com.zhu.transaction.service.OrderService;
import com.zhu.transaction.utils.HttpClient;
import com.zhu.transaction.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author Zhu
 * @createtime 2021/2/14-17:09
 */
@Service
public class OrderServiceImp implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    /**
     * 新增一条订单
     *
     * @param order 订单信息
     * @return 新增结果
     */
    @Override
    public BackState addOneOrder(Order order) {
        order.setId(MyUtils.getRandomID()).setPurchaseTime(new Date()).setUpdateTime(new Date())
                .setPaymentState(PaymentState.NO_PAYMENT).setTransactionState(OrderTransactionState.WAITE_PAYMENT);
        int result = orderMapper.addOneOrder(order);
        return result > 0 ? BackState.SUCCESS : BackState.ERROR;
    }

    /**
     * 获取订单列表
     *
     * @param userId     用户Id
     * @param isPurchase true：获取买方的所有订单信息；false：获取卖方的所有订单信息
     * @return 订单列表
     */
    @Override
    public List<OrderItem> getOrderList(String userId, boolean isPurchase) {
        List<Order> resultList = null;
        if (isPurchase) {
            resultList = orderMapper.queryOrderByPurchaseUserId(userId);
        } else {
            resultList = orderMapper.queryOrderByReleaseUserId(userId);
        }
        return getOrderItems(resultList);
    }

    /**
     * 获取所有订单信息
     *
     * @return 订单列表
     */
    @Override
    public List<OrderItem> getAllOrderList() {
        List<Order> orders = orderMapper.queryAllOrder();
        return getOrderItems(orders);
    }

    /**
     * 获取订单详情
     *
     * @param orderId 订单号
     * @return 订单详细
     */
    @Override
    public List<Order> getOrderListByOrderId(String orderId) {
        return orderMapper.queryOrderByOrderId(orderId);
    }

    /**
     * 删除订单
     *
     * @param orderId 订单号
     * @return 删除结果
     */
    @Override
    public BackState deleteOrder(String orderId) {
        return orderMapper.deleteOrder(orderId) > 0 ? BackState.SUCCESS : BackState.ERROR;
    }

    /**
     * 更新订单状态
     *
     * @param orderId          订单Id
     * @param paymentState     支付状态
     * @param transactionState 订单状态
     * @return 更新结果
     */
    @Override
    public BackState updateOrderState(String orderId, Integer paymentState, Integer transactionState) {
        int paymentResult = orderMapper.updateOrderPaymentState(orderId, paymentState);
        int transactionResult = orderMapper.updateOrderTransactionState(orderId, transactionState);
        return paymentResult + transactionResult > 0 ? BackState.SUCCESS : BackState.ERROR;
    }

    /**
     * 封装订单信息
     *
     * @param orderList 订单列表
     * @return
     */
    private List<OrderItem> getOrderItems(List<Order> orderList) {
        List<OrderItem> orderItemList = new ArrayList<>();
        Map<String, List<Order>> map = new HashMap<>();
        for (Order order : orderList) {
            order.setReleaseUserPojo(userMapper.queryUserByID(order.getReleaseUser()));
        }
        for (Order order : orderList) {
            String orderId = order.getOrderId();
            List<Order> tmpOrderList = map.get(orderId);
            if (tmpOrderList == null) {
                List<Order> orders = new ArrayList<>();
                orders.add(order);
                map.put(orderId, orders);
            } else {
                tmpOrderList.add(order);
            }
        }

        for (Map.Entry<String, List<Order>> orderItemMap : map.entrySet()) {
            List<Order> orders = orderItemMap.getValue();
            StringBuilder productName = new StringBuilder();
            OrderItem orderItem = new OrderItem();
            float totalPrice = 0;
            for (Order order : orders) {
                productName.append(order.getProductName()).append("、");
                totalPrice += order.getPrice();
            }
            orderItem.setOrderId(orderItemMap.getKey()).setProductNames(productName.substring(0, productName.length() - 1))
                    .setOrderState(orders.get(0).getTransactionState()).setAddress(orders.get(0).getAddress())
                    .setOrderList(orders).setPhone(orders.get(0).getPurchaserPhone())
                    .setUserName(orders.get(0).getPurchaseUserName()).setPurchaseTime(orders.get(0).getPurchaseTime()).setTotalPrice(totalPrice);
            orderItemList.add(orderItem);
        }

        return orderItemList;
    }

    /**
     * 生成微信支付接口
     *
     * @param orderNo 订单号
     * @return 微信订单支付二维码等信息
     */
    @Override
    public Map createNative(String orderNo) {
        try {
            //根据订单id获取订单信息
            List<Order> orders = orderMapper.queryOrderByOrderId(orderNo);
            Order order = orders.get(0);

            Map m = new HashMap();
            //1、设置支付参数
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", order.getProductName());
            m.put("out_trade_no", orderNo);
            m.put("total_fee", new BigDecimal("0.01").multiply(new BigDecimal("100")).longValue() + "");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            m.put("trade_type", "NATIVE");

            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集

            String result_code = resultMap.get("result_code");
            String code_url = resultMap.get("code_url");
            Map map = new HashMap<String, String>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getOrderId());
            map.put("total_fee", order.getPrice());
            map.put("result_code", result_code);
            map.put("code_url", code_url);

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<String, String>();
        }
    }

    /**
     * 查询微信支付状态
     *
     * @param orderNo 订单号
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb")); //商户key
            client.setHttps(true);
            client.post();

            //3、得到参数 转成Map  返回
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 连接支付宝支付接口
     *
     * @param orderId 订单号
     * @return 支付宝支付表单
     * @throws IOException
     */
    @Override
    public String createPayForm(String orderId, String totalPrice) throws IOException {
        //通过订单Id查询订单详情
        List<Order> orders = orderMapper.queryOrderByOrderId(orderId);
        Order order = orders.get(0);

        if (order.getPrice() != null) {
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = order.getOrderId();
            // 订单名称，必填
            String subject = order.getProductName();
            // 付款金额，必填
            String total_amount = totalPrice;
            // 商品描述，可空
            String body = "";
            // 超时时间 可空
            String timeout_express = "2m";
            // 销售产品码 必填
            String product_code = "FAST_INSTANT_TRADE_PAY";

            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, AlipayConfig.FORMAT, AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            AlipayTradePagePayRequest alipay_request = new AlipayTradePagePayRequest();

            // 封装请求支付信息(手机端)
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
            model.setTimeoutExpress(timeout_express);
            model.setProductCode(product_code);
            alipay_request.setBizModel(model);

            // 设置异步通知地址
            alipay_request.setNotifyUrl(AlipayConfig.notify_url);
            // 设置同步地址
            alipay_request.setReturnUrl(AlipayConfig.return_url);

            // form表单生产
            String form = "";
            try {
                // 调用SDK生成表单
                form = client.pageExecute(alipay_request).getBody();
            } catch (AlipayApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return form;
        }
        return null;
    }

    /**
     * 接收支付宝返回通知
     *
     * @param aliPayState 支付宝返回参数
     * @return
     */
    @Override
    public Boolean aliPayReturnNotice(AliPayState aliPayState) {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = null;
        try {
            params = MyUtils.bean2map(aliPayState);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //验证上面的信息是不是由支付宝给我们返回的
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //验证成功
        return verify_result;
    }

    @Override
    public BackState updatePayStatus(Order order) {
        return orderMapper.updatePayStatus(order) > 0 ? BackState.SUCCESS : BackState.ERROR;
    }


}
